import { video2gif, welcome, newGifName } from './lib.js';
import inquirer from 'inquirer';
import fs from 'fs';

/**
 * 入口函数
 */
function main() {
  welcome('Video To Gif');
  run();
}

async function run() {

  const answers = await inquirer.prompt([
    {
      type: 'input',
      name: 'video',
      message: '视频路径',
      default: '',
      validate: (value) => {
        if (value.length === 0) {
          return '请输入视频路径';
        }
        value = value.replace(/['"]/g, '');
        if (!fs.existsSync(value)) {
          return '视频路径不存在';
        }
        return true;
      }
    },
    {
      type: 'input',
      name: 'startTime',
      message: '开始时间',
      default: '00:00:00',
      validate: (value) => {
        if (value.length === 0) {
          return '请输入开始时间';
        }
        if (!/^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/.test(value)) {
          return '格式必须是 时:分:秒';
        }
        return true;
      }
    },
    {
      type: 'number',
      name: 'duration',
      message: '截取秒数',
      default: 10,
      validate: (value) => {
        if (value <= 0) {
          return '截取秒数必须大于0';
        }
        return true;
      }
    },
    {
      type: 'list',
      name: 'format',
      message: '图片类型',
      default: 'gif',
      choices: [
        { name: 'gif', value: 'gif' },
        { name: 'webp', value: 'webp' },
      ]
    }
  ])
  answers.video = answers.video.replace(/['"]/g, '');

  const imagePath = newGifName(answers.video, answers.format)
  const result = video2gif(answers.video, imagePath, answers.format, answers.startTime, answers.duration)
  console.log(`☕稍等片刻...`)
  await result
  console.log(`👌完成: ${imagePath}`)

}
main();